package com.example.infrastructure.api.person.validation;

import com.example.infrastructure.api.person.validation.annotation.EnumCheck;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/23 下午2:49
 **/
public class EnumCheckValidator implements ConstraintValidator<EnumCheck, String> {
    private Class<? extends Enum<?>> enumClass;

    @Override
    public void initialize(EnumCheck constraintAnnotation) {
        this.enumClass = constraintAnnotation.enumClass();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!StringUtils.hasText(value)) {
            return false;
        }
        for (Enum<?> enumConstant : this.enumClass.getEnumConstants()) {
            if (value.equals(enumConstant.name())) {
                return true;
            }
        }
        return false;
    }
}
